/**
 * Apr 18, 2014 4:47:12 PM
 */
package elitech.vietnam.myfashion.dialog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;

import org.xmlpull.v1.XmlPullParserException;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import elitech.vietnam.myfashion.LoginActivity;
import elitech.vietnam.myfashion.MainActivity;
import elitech.vietnam.myfashion.R;
import elitech.vietnam.myfashion.entites.Color;
import elitech.vietnam.myfashion.entites.OrderDetail;
import elitech.vietnam.myfashion.entites.Product;
import elitech.vietnam.myfashion.entites.Size;
import elitech.vietnam.myfashion.extend.AsyncTask;
import elitech.vietnam.myfashion.utilities.Utilities;
import elitech.vietnam.myfashion.wsclient.Service;

/**
 * @author Cong
 *
 */
public class QuickAddToCartDialog extends Dialog implements View.OnClickListener {
	
	private MainActivity mContext;
	private Product mProduct;
	
	private TextView mTextName, mTextPrice, mTextTotal, mTextSale;
	private Spinner mColor, mSize;
	private EditText mQuantity;
	private Button mBtnOK, mBtnCancel;
	private LinearLayout mLayColor, mLaySize;
	
	private ArrayList<Color> mListColor = new ArrayList<Color>();
	private ArrayList<Size> mListSize = new ArrayList<Size>();
	private ArrayList<String> mNameColor = new ArrayList<String>();
	private ArrayList<String> mNameSize = new ArrayList<String>();
	
	private ArrayAdapter<String> mAdapterColor;
	private ArrayAdapter<String> mAdapterSize;

	int mTask = 2;
	
	public QuickAddToCartDialog(MainActivity context, Product product) {
		super(context, R.style.Dialog);
		mContext = context;
		mProduct = product;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.quickcartdialog);
		
		mTextName = (TextView) findViewById(R.id.dialog_quickcart_txtName);
		mTextPrice = (TextView) findViewById(R.id.dialog_quickcart_txtPrice);
		mTextSale = (TextView) findViewById(R.id.dialog_quickcart_txtSale);
		mTextTotal = (TextView) findViewById(R.id.dialog_quickcart_txtTotal);
		mColor = (Spinner) findViewById(R.id.dialog_quickcart_spinColor);
		mSize = (Spinner) findViewById(R.id.dialog_quickcart_spinSize);
		mQuantity = (EditText) findViewById(R.id.dialog_quickcart_edtQuantity);
		mBtnCancel = (Button) findViewById(R.id.quickcart_btnCancel);
		mBtnOK = (Button) findViewById(R.id.quickcart_btnOk);
		mLayColor = (LinearLayout) findViewById(R.id.dialog_quickcart_layColor);
		mLaySize = (LinearLayout) findViewById(R.id.dialog_quickcart_laySize);
		
		mTextName.setText(mProduct.Name);
		if (mProduct.SaleOff != 0) {
			mTextSale.setVisibility(View.VISIBLE);
			mTextPrice.setPaintFlags(mTextPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
		}
		mTextSale.setText(Utilities.numberFormat(mProduct.PriceSale) + " VND");
		mTextPrice.setText(Utilities.numberFormat(mProduct.PriceVN) + " VND");
		mTextTotal.setText(Utilities.numberFormat((mProduct.SaleOff != 0) ? mProduct.PriceSale : mProduct.PriceVN) + " VND");
		
		mAdapterColor = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, mNameColor);
		mAdapterColor.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		mColor.setAdapter(mAdapterColor);
		
		mAdapterSize = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, mNameSize);
		mAdapterSize.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		mSize.setAdapter(mAdapterSize);
		
		mBtnCancel.setOnClickListener(this);
		mBtnOK.setOnClickListener(this);
		
		mQuantity.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (!mQuantity.getText().toString().equals("")) {
					int count1 = Integer.parseInt(mQuantity.getText().toString());
					if (count1 > 10) {
						mQuantity.setText("");
						mQuantity.append("10");
					} else
						mTextTotal.setText(Utilities.numberFormat(((mProduct.SaleOff != 0) ? mProduct.PriceSale : mProduct.PriceVN) * count1) + " VND");
				}
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}
			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		
		LoadData();
	}
	
	@Override
	public void onClick(View v) {
		InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(mQuantity.getWindowToken(), 0);
		switch (v.getId()) {
		case R.id.quickcart_btnCancel:
			dismiss();
			break;
		case R.id.quickcart_btnOk:
			if (mContext.mUser == null) {
				Intent i = new Intent(mContext, LoginActivity.class);
				mContext.startActivityForResult(i, MainActivity.LOGINACTIVITY);
				dismiss();
			} else if (mQuantity.getText().toString().length() == 0 || Integer.parseInt(mQuantity.getText().toString()) <= 0)
					Toast.makeText(mContext, R.string.invalidquantity, Toast.LENGTH_SHORT).show();
			else {
				if (mLayColor.getVisibility() == View.VISIBLE)
					mProduct.Color = mListColor.get(mColor.getSelectedItemPosition());
				if (mLaySize.getVisibility() == View.VISIBLE)
					mProduct.Size = mListSize.get(mSize.getSelectedItemPosition());
				mProduct.Quantity = Integer.parseInt(mQuantity.getText().toString());
	
				OrderDetail detail = new OrderDetail();
				detail.ProductID = mProduct.Id;
				detail.ProductName = mProduct.Name;
				detail.CategoryNameEN = mProduct.CategoryNameEN;
				detail.CategoryNameVN = mProduct.CategoryNameVN;
				detail.CategoryNameKR = mProduct.CategoryNameKR;
				detail.Price = mProduct.Price - mProduct.Price
						* mProduct.SaleOff / 100;
				detail.PriceVN = (mProduct.SaleOff != 0) ? mProduct.PriceSale : mProduct.PriceVN;
				if (mProduct.Color != null) {
					detail.ColorNameEN = mProduct.Color.NameEN;
					detail.ColorNameKR = mProduct.Color.NameKR;
					detail.ColorNameVN = mProduct.Color.NameVN;
					detail.Color = mProduct.Color.ColorID;
				} else {
					detail.Color = -1;
				}
				if (mProduct.Size != null) {
					detail.SizeName = mProduct.Size.Size;
					detail.Size = mProduct.Size.SizeID;
				} else {
					detail.Size = -1;
				}
				detail.Quantity = mProduct.Quantity;
				detail.Image = mProduct.Image;
				detail.SaleOff = mProduct.SaleOff;
	
				AddToCart(detail);
				Toast.makeText(mContext, mContext.getString(R.string.addsuccess), Toast.LENGTH_SHORT).show();
				dismiss();
			}
			break;
		default:
			break;
		}
	}

	private void LoadData() {
		mBtnOK.setEnabled(false);
		mLayColor.setVisibility(View.GONE);
		mLaySize.setVisibility(View.GONE);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		new AsyncTask<Integer, Integer, Boolean>() {
			@Override
			protected Boolean doInBackground(Integer... params) {
				try {
					if (mProduct.ColorList.isEmpty())
						mProduct.ColorList.addAll(new Service().getProductColor(mProduct.Id));
				} catch (IOException e) {
					return false;
				} catch (XmlPullParserException e) {
					return false;
				}
				return null;
			}
			protected void onPostExecute(Boolean result) {
				if (!isShowing())
					return;
				if (result != null) {
					new WarningDialog(mContext, mContext.getString(R.string.connecterror)).show();
					dismiss();
					return;
				}
				if (!mProduct.ColorList.isEmpty()) {
					mListColor.clear();
					mNameColor.clear();
					mListColor.addAll(mProduct.ColorList);
					for (Color color : mProduct.ColorList) 
						if (mContext.getLocale().equals(Locale.ENGLISH))
							mNameColor.add(color.NameEN);
						else if (mContext.getLocale().equals(Locale.KOREA))
							mNameColor.add(color.NameKR);
						else
							mNameColor.add(color.NameVN);
//					mNameColor.add(mContext.getString(R.string.selectone));
					mLayColor.setVisibility(View.VISIBLE);
					mAdapterColor.notifyDataSetChanged();
//					mColor.setSelection(mNameColor.size() - 1);
				}
				Loaded();
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		new AsyncTask<Integer, Integer, Boolean>() {
			@Override
			protected Boolean doInBackground(Integer... params) {
				try {
					if (mProduct.SizeList.isEmpty())
						mProduct.SizeList.addAll(new Service().getProductSize(mProduct.Id));
				} catch (IOException e) {
					return false;
				} catch (XmlPullParserException e) {
					return false;
				}
				return null;
			}
			protected void onPostExecute(Boolean result) {
				if (!isShowing())
					return;
				if (result != null) {
					new WarningDialog(mContext, mContext.getString(R.string.connecterror)).show();
					dismiss();
					return;
				}
				if (!mProduct.SizeList.isEmpty()) {
					mListSize.clear();
					mNameSize.clear();
					mListSize.addAll(mProduct.SizeList);
					for (Size color : mProduct.SizeList) 
						mNameSize.add(color.Size);
//					mNameSize.add(mContext.getString(R.string.selectone));
					mLaySize.setVisibility(View.VISIBLE);
					mAdapterSize.notifyDataSetChanged();
//					mSize.setSelection(mNameSize.size() - 1);
				}
				Loaded();
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}
	
	private synchronized void Loaded() {
		mTask -= 1;
		if (mTask != 0) 
			return;
		mBtnOK.setEnabled(true);
	}

	private void AddToCart(OrderDetail order) {
		for (OrderDetail detail : mContext.mOrder.ListDetail) {
			if (detail.ProductID == order.ProductID
					&& detail.Size == order.Size && detail.Color == order.Color) {
				detail.Quantity = detail.Quantity + order.Quantity;
				return;
			}
		}
		mContext.mOrder.ListDetail.add(order);
	}
}
